<?php

namespace app\actions;

use app\components\BaseController;
use app\utils\BaseUtils;
use yii\base\Action;
use yii\imagine\Image;

class UploadAction extends Action {

    /* @var $controller BaseController */
    public $controller;

    public function run() {
        if (empty($_FILES)) {
            return $this->error('empty Upload');
        }

        $allowExt = array('jpg', 'gif', 'png', 'bmp', 'jpeg');
        $data = [];
        foreach ($_FILES as $_file) {
            if ($_file['error'] > 0) {
                return $this->error('上传错误');
            }
            $res = $this->__upload($_file, $allowExt);
            if ($res['code'] != 0) {
                return $res;
            }
            $data[] = $res['data'];
        }

        $mid = \Yii::$app->controller->module->id;
        if ($mid != 'api' && count($data) <= 1) {
            $data = current($data);
        }
        return $this->controller->success($data);
    }

    protected function __upload($_file, $allowExt = []) {
        $dir = $this->controller->get('dir', date('Ym'));

        $path = "/uploads/{$dir}/";
        $absolutePath = APP_ROOT . $path;
        if (!BaseUtils::is_writable_dir($absolutePath)) {
            return $this->error('上传目录不可写.');
        }

        BaseUtils::mkdir($absolutePath);

        $fileExt = strtolower(pathinfo($_file['name'], PATHINFO_EXTENSION));
        $fileExt = str_replace('jpeg', 'jpg', $fileExt);
        $fileName = strtoupper(substr(md5(uniqid()), 8, 16)) . ".{$fileExt}";

        if (!empty($allowExt) && !in_array($fileExt, $allowExt, TRUE)) {
            return $this->error('上传文件类型不允许.');
        }

        $fileAbsolutePath = $absolutePath . $fileName;
        if (!move_uploaded_file($_file['tmp_name'], $fileAbsolutePath)) {
            return $this->error('保存文件失败');
        }

        $file = $path . $fileName;
        $src = \Yii::$app->request->getHostInfo() . $file;

        $is_compress = \Yii::$app->request->get('not_compress');
        if (NULL === $is_compress) {
            BaseUtils::thumb($fileAbsolutePath, 800, 800);
        }

        return $this->success(['file' => $file, 'src' => $src]);
    }

    protected function success($data) {
        $type = $this->controller->get('type');
        if ($type == 'edit') {
            return $this->controller->exitJson(['url' => $data['file'], 'error' => 0]);
        }
        return $this->controller->success($data);
    }

    protected function error($msg) {
        $type = $this->controller->get('type');
        if ($type == 'edit') {
            return $this->controller->exitJson(['message' => $msg, 'error' => 1]);
        }
        return $this->controller->error($msg);
    }
}